/* Copyright 2011 Rok Lenarčič 
 * 
 * This file is a part of MicroFn.
 * 
 * MicroFn is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * MicroFn is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.

 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/> */

package net.rlenar.microfn;

import java.util.Comparator;
import java.util.concurrent.Callable;


public abstract class Fn implements IFn, Runnable, Comparator<Object>, Callable<Object> {
	private int minArgs;
	private int maxArgs;
	public Fn(int minArgs, int maxArgs) {
		this.maxArgs = maxArgs;
		this.minArgs = minArgs;
	}
	public Fn(int minArgs) {
		this(minArgs, Integer.MAX_VALUE);
	}
	public Fn() {
		this(0, Integer.MAX_VALUE);
	}
	protected boolean checkArity(Object[] args) {
		return (args.length >= minArgs) && (args.length <= maxArgs);			
	}
	protected String getExpectedArityString() {
        if (minArgs == maxArgs) {
            return String.valueOf(minArgs);
        } else {
            return minArgs + " to " + maxArgs;
        }	    
	}
	
	public final Object invoke(Object... args) {
		if (checkArity(args)) {
			try {
				return doFunc(args);
			} catch (RuntimeException e) {
				if (!(e instanceof FnException)) {
					throw new FnException(e, this, args);
				} else {
					throw e;
				}
			} catch (Exception e) {
				throw new FnException(e, this, args);
			}
		} else {
			StringBuilder buf = new StringBuilder("Wrong arity for Fn");
			buf.append(": expected ");
			buf.append(getExpectedArityString());
			buf.append(" arguments, invoked with ");
			buf.append(args.length);
			buf.append(" arguments.");
			throw new FnException(buf.toString(), this, args);
		}
	}
	protected abstract Object doFunc(Object... args) throws Exception; 
	public Object call() throws Exception {
		return invoke();
	}
	private Object runResult = null;
	public void run() {
		runResult = invoke();
	}
	public Object getRunResult() {
		return runResult;
	}
	
    public static boolean isNil(Object obj) {
        if (obj == null) {
            return true;
        } else if (obj instanceof Boolean && !(Boolean)obj) {
            return true;
        } else {
            return false;
        }
    }

	public int compare(Object o1, Object o2) {
		return ((Number)invoke(o1,o2)).intValue();
	}
}
